function goUrl(url){
    window.location.href=url;
}

function regCheck(type, value, that) {
    switch (type) {
        //手机
        case 'mobile':
            if (!(/^1[34578]\d{9}$/.test(value))) {
                return false;
            } else {
                return true;
            }
            break;
        //最小值
        case 'min':

            if (value >= that.data('min')) {
                return true
            } else {
                return false;
            }
            break;
        //最大值
        case 'max':

            if (value >= that.data('max')) {
                return true
            } else {
                return false;
            }
            break;
        //是否是数字
        case 'number':

            if (value == 0) {
                return true;
            }
            if (isNaN(value)) {
                return false
            } else {
                return true;
            }
            break;
        //英文
        case 'ename':
            if (!new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$").test(value)) {
                return false
            } else {
                return true
            }
            break
        //中文
        case 'cn':
            if (!new RegExp("^[\u4e00-\u9fa5]+$").test(value)) {
                return false;
            } else {
                return true
            }
            break;
        //字符串限制
        case 'str_limit':
            var max = that.data('max');
            if (value.length > max) {
                return false;
            } else {
                return true
            }
            break;
        case 'url':
            if (!new RegExp("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\*\\+,;=.]+$").test(value)) {
                return false;
            } else {
                return true
            }
            break;
        case 'email':
            if (!new RegExp("^\\w+((.\\w+)|(-\\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$").test(value)) {
                return false;
            } else {
                return true
            }
            break;
        case 'ip':
            if (!new RegExp("(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])").test(value)) {
                return false;
            } else {
                return true
            }
            break;

    }
    return false;
}
function ajaxSubmit(obj, callFun, cover) {
    obj = obj || '.ajax-submit';
    cover = cover || 0;
    $(document).on('click', obj, function () {

        var btn = $(this);
        var go = true;
        var form = $(this).parents('form');

        var url = form.attr('action');
        var method = form.attr('method');
        var rest_method = form.find("input[name='_method']");
        var method_s = rest_method.length > 0 ? rest_method.val() : method;
        var status = 1;
        form.find('[data-rq="1"],[rq="1"]').each(function () {

            var value = $(this).val();

            var reg = $(this).data('reg');//是否又正则验证
            var reg_zz = $(this).data('reg_tip');
            var tips = $(this).data('tip');
            tips = tips ? tips : $(this).attr('placeholder');
            if (value == '') {

                msg(tips);
                status = 0;
                $(this).focus();
                return false;
            } else {
                if (reg) {
                    if (!regCheck(reg, value, $(this))) {
                        msg(reg_zz || tips);
                        status = 0;
                        return false;
                    }
                }

            }
        });
        if (status == 0) {
            return false;
        }
        //是否单独设置返回地址
        var form_back = form.find('[name="back_url"]').val();
        btn.attr('disabled', true);

        if (go == true) {

            var do_toast = msgToast('提交中...', 0, 'loading');
            $.ajax({
                type: method_s,
                url: url,
                data: form.serialize(),
                dataType: "json",
                success: function (data) {
                    btn.attr('disabled', false);
                    if (data.code == 1000) {
                        do_toast.close();
                        return msgConfirm('您还没有登录，现在进入登录？', function () {
                            goUrl(urlConfigApi.loginUrl)
                        });

                    }


                    if (cover) {
                        do_toast.close();
                        callFun && callFun(data);
                    } else {
                        callFun && callFun(data);
                        if (data.code == 200) {

                            msgToastUpOk(do_toast, data.msg, 2000, function () {

                                setTimeout(function () {
                                    if (form_back) {
                                        window.location.href = form_back;
                                    } else {
                                        if (data.data.url) {
                                            window.location.href = data.data.url;
                                        }
                                        if (data.data['self']) {
                                            window.location.reload();//刷新自己
                                        }

                                    }
                                }, 0)

                            })

                        } else {
                            msg(data.msg);

                            do_toast.close();
                        }
                    }

                },
                complete: function () {
                    //do_toast.close();
                },
                error: function () {
                    do_toast.close();
                    btn.attr('disabled', false);
                    msg('系统异常，请联系我们或稍后再试');
                }
            });
        }
    })
}
function ajax(url, data, success, fail, complete, method, header, async, closeAuth) {
    data = data || {}
    header = header || {};
    closeAuth = closeAuth || 0;

    method = method || 'post';
    if (async == 0) {
        async=0;
    } else {
        async = 1;
    }
    data._token=$('[name="csrf-token"]').attr('content');
    //console.log('是否异步形式',async);
    let headerObj = {};
    for (let i in header) {
        headerObj[i] = header[i];
    }
    //console.log('ajax headerObj',headerObj);
    $.ajax({
        data: data,
        //headers: headerObj,
        async: async,    //表示请求是否异步处理
        type: method,    //请求类型
        url: url,//请求的 URL地址
        dataType: "json",//返回的数据类型
        success: function (res) {
            if (!closeAuth) {
                if (res.code == 1000) {

                    return msgConfirm('您还没有登录，现在进入登录？', function () {
                        goUrl(urlConfigApi.loginUrl)
                    });

                }
            }

            return success && success(res)
        },
        error: function (res) {
            return fail && fail(res)
        },
        complete(res) {

            return complete && complete(res)
        }
    });

}

function msg(msg, title, time, true_btn, afterFun) {
    true_btn = true_btn || 0;
    title = title || '提示';
    if (time != 0) {
        time = time * 1000 || 2500;
    }
    $(document).dialog({
        titleText: title,
        content: msg,
        closeFootBtn: true_btn,
        autoClose: time
    });
    setTimeout(function () {
        afterFun && afterFun();
    }, time)
}

/**
 * Notice类型
 * @param msg
 * @param time
 * @param afterFun
 */
function msgNotice(msg, time, afterFun) {

    if (time != 0) {
        time = time * 1000 || 2000;
    }
    $(document).dialog({

        type: 'notice',
        infoText: msg,
        autoClose: time
    });
    setTimeout(function () {
        afterFun && afterFun();
    }, time)
}

function msgToast(msg, time, type, afterFun) {
    if (time != 0) {
        time = time || 2500;
    }
    type = type || 'info';

    msg = msg || '正在加载中'
    var toast = $(document).dialog({
        type: 'toast',
        infoIcon: dialogIcon[type],
        infoText: msg,
        autoClose: time,
        overlayShow: true
    });
    afterFun && afterFun(toast);
    return toast;
}

/**
 * 从toast转换到其他更新图标
 * @param toast
 * @param msg
 * @param time
 * @param afterFun
 */
function msgToastUpOk(toast, msg, time, afterFun) {
    if (time != 0) {
        time = time || 2500;
    }

    toast.update({
        infoIcon: dialogIcon.success,
        infoText: msg,
        autoClose: time,
    });

    setTimeout(function () {

        afterFun && afterFun(toast);
    }, time)
}

//带提交操作的弹出信息
function msgNoticeDonig(msg, okmsg, time, closeTime, afterFun) {
    if (time != 0) {
        time = time || 2500;
    }
    closeTime = closeTime || 2500
    var notice5 = $(document).dialog({
        type: 'notice',
        infoIcon: dialogIcon.loading,
        infoText: msg
    });

    setTimeout(function () {
        notice5.update({
            infoIcon: dialogIcon.success,
            infoText: okmsg,
            autoClose: closeTime
        });
        afterFun && afterFun();
    }, time);
}

function msgConfirm(msg, res, cancle, title, btn) {
    btn = btn || ['确定', '取消'];
    title = title || '提示';
    $(document).dialog({
        type: 'confirm',
        closeBtnShow: true,
        titleText: title,
        content: msg,
        closeBtnShow: false,
        buttonTextConfirm: btn[0],
        buttonTextCancel: btn[1],
        onClickConfirmBtn: function () {
            res && res()
        },
        onClickCancelBtn: function () {
            cancle && cancle()
        }

    });

}

$(function () {
    ajaxSubmit();
    $(".sendEmail").click(function(){
        var email=$(".sendEmailVal").val();
        var type='email';
        if(!email)
        {
            $("sendEmailVal").focus();
            return msg('请输入邮箱');
        }
        ajax(urlConfigApi.emailSend,{email:email,type:type},function(res){
            msg(res.msg);
        })
    });
    $(".sendEmail2").click(function(){
        var email=$(".sendEmailVal2").val();
        var type='email';
        if(!email)
        {
            $("sendEmailVal2").focus();
            return msg('请输入邮箱');
        }
        ajax(urlConfigApi.emailSend,{email:email,type:type},function(res){
            msg(res.msg);
        })
    });
});